package cn.zhaopin.starter.security.filter;

import cn.zhaopin.common.constant.LogConstants;
import cn.zhaopin.starter.security.common.SecurityConstant;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;

import java.util.UUID;

/**
 * Description: trace过滤器
 *
 * @author zuomin (myleszelic@outlook.com)
 * @date: 2021/10/29-17:20
 */
@Slf4j
public class TraceFilter implements WebFilter {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
        String traceId = UUID.randomUUID().toString().replace("-", "");
        ServerHttpRequest serverHttpRequest = exchange.getRequest().mutate()
                .headers(h -> h.add(SecurityConstant.HEADER_TRACE_ID, traceId))
                .build();

        exchange = exchange.mutate().request(serverHttpRequest).build();
        MDC.put(LogConstants.LOG_TRACE_ID, traceId);
        return chain.filter(exchange);
    }
}